package com.glory.hikvisionmobile.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.LotScrap.ScrapBean;
import com.glory.hikvisionmobile.bean.LotScrap.ScrapListBean;
import com.glory.hikvisionmobile.bean.mapping.CarrierNumBean;
import com.glory.hikvisionmobile.bean.mapping.ComponentBean;
import com.glory.hikvisionmobile.bean.mapping.ComponentIdBean;
import com.glory.hikvisionmobile.bean.mapping.MapPingBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.customView.MapDivider;
import com.glory.hikvisionmobile.customView.RtlGridLayoutManager;
import com.glory.hikvisionmobile.utils.EditTextEnterUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.yzq.zxinglibrary.android.CaptureActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author yi.zhang
 * @date 2019/11/27
 * @desc MAPPING 图
 */
public class Work_MapPingActivity extends BaseActivity {

    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.canvas_Rv)
    RecyclerView canvasRv;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.ivTypeArrow)
    ImageView ivTypeArrow;
    @BindView(R.id.flMapTypeList)
    FrameLayout flMapTypeList;
    @BindView(R.id.tvCarrierNum)
    TextView tvCarrierNum;
    @BindView(R.id.ivCarrierNumArrow)
    ImageView ivCarrierNumArrow;
    @BindView(R.id.flCarrierNumList)
    FrameLayout flCarrierNumList;
    @BindView(R.id.llSubmitLayout)
    LinearLayout llSubmitLayout;
    @BindView(R.id.tvLotId)
    TextView tvLotId;
    @BindView(R.id.tvComponentId)
    TextView tvComponentId;
    @BindView(R.id.tvScrap)
    TextView tvScrap;
    @BindView(R.id.ivScrapListArrow)
    ImageView ivScrapListArrow;
    @BindView(R.id.flScrapList)
    FrameLayout flScrapList;
    @BindView(R.id.etRemarks)
    FreeUI_ClearEditText etRemarks;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    @BindView(R.id.tvSearch)
    TextView tvSearch;


    private List<String> typeList;
    private BaseQuickAdapter adapter;
    private String type = "All";
    private List<String> carrierList = new ArrayList<>();
    private FreeUI_GeneralPop carrierPop;
    private FreeUI_GeneralPop typePop;
    private FreeUI_GeneralPop ScrapPop;
    private List<String> scrapList = new ArrayList<>();
    private List<String> unScrapList = new ArrayList<>();
    private boolean isScrap = false;
    private String scrapCode;
    private int lastPosition = -1;

    private static final int SCANNER_REQUEST_CODE = 10;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_mapping;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            super.onSaveInstanceState(outState);
        }
    }

    @Override
    protected void initView() {
        tvType.setText("全部");
        EditTextEnterUtils.initEnter(etLot, text -> {
            carrierList.clear();
            tvCarrierNum.setText("");
            requestCarrierList(text, null, "lotIdQuery");
        });
        typeList = new ArrayList<>();
        typeList.add("全部");
        typeList.add("已报废");
        typeList.add("未报废");

    }

    /**
     * 请求载具编号接口和请求mapPing信息接口，通过actionType判断
     *
     * @param lotId
     */
    private void requestCarrierList(String lotId, String carrierId, String actionType) {
        JsonObject map = new JsonObject();
        map.addProperty("lotId", lotId);
        map.addProperty("actionType", actionType);
        map.addProperty("durableNum", carrierId);

        NetUtils.requestDara("HIK.PdaMappingQuery", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<MapPingBean>>
                (new TypeToken<BaseResponseBean<MapPingBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<MapPingBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    MapPingBean data = response.body().getBody();

                    if (actionType.equals("lotIdQuery")){
                        List<CarrierNumBean> durableNums = data.getDurableNums();
                        if (durableNums.size() <= 0){
                            showConfirmDialog("载具编号为空");
                            return;
                        }
                        for (CarrierNumBean carrierNumBean : durableNums) {
                            carrierList.add(carrierNumBean.getDurableNum());
                        }
                        tvCarrierNum.setText(carrierList.get(0));
                        requestCarrierList(lotId, carrierList.get(0), "lotIdCarrierQuery");
                    }

                    if (actionType.equals("lotIdCarrierQuery")) {
                        if (data.getxNum()<= 0 | data.getyNum() <= 0 | data.getxPdaComponentByXYs().size() <= 0){
                            showConfirmDialog("MES传回数值为空");
                            return;
                        }
                        //初始化列表
                        initRecyclerView(data);
                    }

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<MapPingBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaMappingQuery");
            }
        });

    }

    private void initRecyclerView(MapPingBean data) {
        //排序
        List<ComponentBean> componentBeans = data.getxPdaComponentByXYs();
        Comparator<ComponentBean> byX = Comparator.comparing(ComponentBean::getDieY);
        Comparator<ComponentBean> byY = Comparator.comparing(ComponentBean::getDieX);
        Collections.sort(componentBeans, byX.thenComparing(byY));
        //增加坐标信息
        for (int i = 0; i < data.getxNum() + 1; i++) {
            if (i == 0){
                ComponentBean componentBean = new ComponentBean();
                componentBean.setIsHaveVal(-2);
                componentBeans.add(i,componentBean);
                continue;
            }
            ComponentBean componentBean = new ComponentBean();
            componentBean.setSeq(String.valueOf(i));
            componentBean.setIsHaveVal(-2);
            componentBeans.add(i,componentBean);
        }

        int y = 1;
        for (int i = 1; i < componentBeans.size(); i++) {
            if (i % (data.getxNum() + 1) == 0){
                ComponentBean componentBean = new ComponentBean();
                componentBean.setSeq(String.valueOf(y++));
                componentBean.setIsHaveVal(-2);
                componentBeans.add(i,componentBean);
            }
        }
        RtlGridLayoutManager layoutManager = new RtlGridLayoutManager(Work_MapPingActivity.this, data.getxNum() + 1);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return 0;
            }
        });
        canvasRv.setLayoutManager(layoutManager);
        if (canvasRv.getItemDecorationCount() == 0){
            canvasRv.addItemDecoration(new MapDivider(this));
        }
        adapter = new BaseQuickAdapter<ComponentBean, BaseViewHolder>(R.layout.item_mapping, componentBeans) {
            @Override
            protected void convert(BaseViewHolder helper, ComponentBean item) {
                helper.setText(R.id.tv_item, item.getSeq());
                viewDisplayControl(helper, item);
                //可以放置组件，但是没有放置
                if (item.getIsHaveVal() == 0) {
                    helper.setBackgroundColor(R.id.tv_item, getResources().getColor(R.color.white));
                } else if (item.getIsHaveVal() == 1) {
                    //可以报废组件还是取消报废组件
                    if (item.getXPdaComponent().getState().equals("SCRAP")) {
                        helper.setBackgroundColor(R.id.tv_item, getResources().getColor(R.color.red));
                    } else {
                        helper.setBackgroundColor(R.id.tv_item, getResources().getColor(R.color.green));
                    }
                } else{
                    //不可以放置组件
                    helper.setBackgroundColor(R.id.tv_item, getResources().getColor(R.color.ll_graybg));
                }
                //选中颜色
                if (item.isCheck()) {
                    helper.setBackgroundColor(R.id.tv_item, getResources().getColor(R.color.blue));
                }
            }
        };
        canvasRv.setAdapter(adapter);

        adapter.setOnItemClickListener((adapter, view, position) -> {
            ComponentBean componentBean = data.getxPdaComponentByXYs().get(position);
            if (componentBean.getIsHaveVal() != 1) {
                //清除上一次点击的状态
                if (lastPosition >= 0){
                    data.getxPdaComponentByXYs().get(lastPosition).setCheck(false);
                    adapter.notifyItemChanged(lastPosition);
                    lastPosition = position;
                }
                showToast("当前坐标无组件信息", false);
                llSubmitLayout.setVisibility(View.INVISIBLE);
                return;
            }
            if (lastPosition == -1){
                lastPosition = position;
            }else if (position == lastPosition){
                return;
            }else if (position != lastPosition && lastPosition != -1){
                data.getxPdaComponentByXYs().get(lastPosition).setCheck(false);
                adapter.notifyItemChanged(lastPosition);
                lastPosition = position;
            }

            componentBean.setCheck(true);
            adapter.notifyItemChanged(position);
            ComponentIdBean xPdaComponent = componentBean.getXPdaComponent();
            isScrap = !xPdaComponent.getState().equals("SCRAP");
            ScrapPop = null;
            tvLotId.setText(etLot.getText().toString());
            tvComponentId.setText(xPdaComponent.getComponentId());
            tvScrap.setText("");
            etRemarks.setText("");
            llSubmitLayout.setVisibility(View.VISIBLE);
            tvReplay.setOnClickListener(view1 -> {
                String remarks = etRemarks.getText().toString().trim();
                if (FreeApi_StringUtils.isEmpty(scrapCode)){
                    showToast("请选择" + (isScrap ? "报废码" : "取消报废码"),false);
                    return;
                }

                if (isScrap){
                    submitScrapInfo(tvLotId.getText().toString().trim(),tvComponentId.getText().toString().trim(),scrapCode,remarks,position);
                }else {
                    submitUnScrapInfo(tvLotId.getText().toString().trim(),tvComponentId.getText().toString().trim(),scrapCode,remarks,position);
                }
            });
        });
    }

    private void submitScrapInfo(String lot, String component, String scrapCode, String remarks,int position) {
        JsonObject json = new JsonObject();
        List<ScrapListBean> scrapList = new ArrayList<>();
        ScrapListBean scrapListBean = new ScrapListBean();
        scrapListBean.setActionCode(scrapCode);
        scrapListBean.setComponentId(component);
        scrapList.add(scrapListBean);
        json.add("XPdaComponent", new JsonParser().parse(new Gson().toJson(scrapList)).getAsJsonArray());
        JsonObject map = new JsonObject();
        map.addProperty("lotId", lot);
        map.addProperty("actionType", "Scrap");
        map.addProperty("scrapComment", remarks);
        map.add("xPdaComponents", json);
        map.addProperty("actionCode",scrapCode);
        NetUtils.requestDara("HIK.PdaLotScrap", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ScrapBean>>(
                new TypeToken<BaseResponseBean<ScrapBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ScrapBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    showConfirmDialog("报废成功");
                    llSubmitLayout.setVisibility(View.INVISIBLE);
                    requestCarrierList(etLot.getText().toString().trim(), tvCarrierNum.getText().toString().trim(), "lotIdCarrierQuery");
                    if (lastPosition >= 0){
                        lastPosition = -1;
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ScrapBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaLotScrap");
            }
        });
    }

    private void submitUnScrapInfo(String lot, String component, String scrapCode, String remarks,int position) {
        JsonObject json = new JsonObject();
        List<ScrapListBean> scrapList = new ArrayList<>();
        ScrapListBean scrapListBean = new ScrapListBean();
        scrapListBean.setActionCode(scrapCode);
        scrapListBean.setComponentId(component);
        scrapList.add(scrapListBean);
        json.add("XPdaComponent", new JsonParser().parse(new Gson().toJson(scrapList)).getAsJsonArray());
        JsonObject map = new JsonObject();
        map.addProperty("lotId", lot);
        map.addProperty("actionType", "UnScrap");
        map.addProperty("scrapComment", remarks);
        map.add("xPdaComponents", json);
        map.addProperty("actionCode",scrapCode);
        NetUtils.requestDara("HIK.PdaLotUnScrap", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ScrapBean>>(
                new TypeToken<BaseResponseBean<ScrapBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ScrapBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    if (FreeApi_StringUtils.isEmpty(response.body().getBody().getNewLotId())){
                        showConfirmDialog("取消报废成功");
                    }else {
                        showConfirmDialog("取消报废成功,新批次：" + response.body().getBody().getNewLotId());
                    }

                    llSubmitLayout.setVisibility(View.INVISIBLE);
                    requestCarrierList(etLot.getText().toString().trim(), tvCarrierNum.getText().toString().trim(), "lotIdCarrierQuery");
                    if (lastPosition >= 0){
                        lastPosition = -1;
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ScrapBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaLotUnScrap");
            }
        });
    }


    private void viewDisplayControl(BaseViewHolder helper, ComponentBean data) {
        switch (type) {
            case "All":
                helper.setVisible(R.id.tv_item, true);
                break;
            case "scrap":
                if (data.getIsHaveVal() == 1 && !data.getXPdaComponent().getState().equals("SCRAP")) {
                    helper.setVisible(R.id.tv_item, false);
                }
                break;
            case "notscrapped":
                if (data.getIsHaveVal() == 1 && data.getXPdaComponent().getState().equals("SCRAP")) {
                    helper.setVisible(R.id.tv_item, false);
                }
                break;
        }
    }

    @Override
    protected void initData() {
        NetUtils.getSelectorList("ScrapCode", "USER", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                scrapList.clear();
                scrapList.addAll(list);
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });

        NetUtils.getSelectorList("UnScrapCode", "USER", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                unScrapList.clear();
                unScrapList.addAll(list);
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });
    }

    private boolean isTabletDevice(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >=
                Configuration.SCREENLAYOUT_SIZE_LARGE;
    }


    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("MAPPING图");
        freeUI_titleView.setRightListener("扫一扫", (v) -> {
            Intent intent = new Intent(Work_MapPingActivity.this, CaptureActivity.class);
            startActivityForResult(intent, SCANNER_REQUEST_CODE);
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == SCANNER_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null) {

                String content = data.getStringExtra(Constant.CODED_CONTENT);
                if (FreeApi_StringUtils.isEmpty(content)){
                    showToast("未扫描到批次，请重新扫描",false);
                }else {
                    carrierList.clear();
                    tvCarrierNum.setText("");
                    etLot.setText(content);
                    requestCarrierList(content, null, "lotIdQuery");
                }
            }
        }
    }


    @OnClick({R.id.flMapTypeList, R.id.flCarrierNumList,R.id.flScrapList,R.id.tvReplay,R.id.tvSearch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flMapTypeList:
                if (typePop != null) {
                    if (typePop.isShowing()) {
                        typePop.dismiss();
                    }
                } else {
                    typePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flMapTypeList.getWidth(), typeList, ivCarrierNumArrow, (codeS, i) -> {
                        tvType.setText(codeS);
                        if (codeS.equals("全部")) {
                            type = "All";
                        } else if (codeS.equals("已报废")) {
                            type = "scrap";
                        } else if (codeS.equals("未报废")) {
                            type = "notscrapped";
                        }

                        search();
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivTypeArrow);
                typePop.showAsDropDown(flMapTypeList, 0, 0);
                break;
            case R.id.flCarrierNumList:
                if (FreeApi_StringUtils.isEmpty(etLot.getText().toString().trim())){
                    showToast("批次号不能为空", false);
                    return;
                }

                if (carrierList.size() <= 0) {
                    showToast("当前批次未查询到载具编号信息", false);
                    return;
                }
                if (carrierPop != null) {
                    if (carrierPop.isShowing()) {
                        carrierPop.dismiss();
                    }
                } else {
                    carrierPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flCarrierNumList.getWidth(), carrierList, ivCarrierNumArrow, (codeS, i) -> {
                        tvCarrierNum.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivCarrierNumArrow);
                carrierPop.showAsDropDown(flCarrierNumList, 0, 0);
                break;
            case R.id.flScrapList:
                if (ScrapPop != null) {
                    if (ScrapPop.isShowing()) {
                        ScrapPop.dismiss();
                    }
                } else {
                    ScrapPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flScrapList.getWidth(), isScrap ? scrapList : unScrapList, ivScrapListArrow, (codeS, i) -> {
                        tvScrap.setText(codeS);
                        scrapCode = codeS.split("/")[0];
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivScrapListArrow);
                ScrapPop.showAsDropDown(flScrapList, 0, 0);
                break;
            case R.id.tvSearch:
               search();
                break;
        }
    }

    private void search() {
        String carrierNum = tvCarrierNum.getText().toString().trim();
        String lotID = etLot.getText().toString().trim();
        if (FreeApi_StringUtils.isEmpty(carrierNum)) {
            showToast("载具编号不能为空", false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(lotID)) {
            showToast("批次号不能为空", false);
            return;
        }
        llSubmitLayout.setVisibility(View.INVISIBLE);
        requestCarrierList(lotID, carrierNum, "lotIdCarrierQuery");
    }

}
